<?php

namespace App\Http\Controllers;

use App\Imports\PhotoArchivesImport;
use App\Services\AttachmentService;
use App\Services\BaseService;
use App\Services\CommonService;
use App\Services\ErrorMsgService;
use App\Services\PhotoArchivesService;
use App\Services\PhotoClassifyService;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;
use PHPUnit\Util\Exception;
use Illuminate\Http\JsonResponse;
use App\Exceptions\ApiException;

class PhotoArchivesController extends BaseController
{
    protected $photoArchivesService;

    public function __construct(PhotoArchivesService $photoArchivesService)
    {
        parent::__construct();
        $this->photoArchivesService = $photoArchivesService;
    }

    /**
     * 照片档案列表
     *
     * @param Request $request
     * @return JsonResponse
     * @author: lxk
     * @date: 2024/3/19 9:03
     */
    public function index(Request $request) : JsonResponse
    {
        $partCompanyId   = $request->input('part_company_id');
        $photoClassifyId = $request->input('photo_classify_id');
        $perPage         = $request->input('per_page') ?: $this->limit;
        $keyword         = format_str($request->input('keyword'));
        $type            = $request->input('type');
        $searchType      = $request->input('search_type');
        if ($photoClassifyId == -1) {
            return $this->success([]);
        }
        if (PhotoClassifyService::isHaveChild($photoClassifyId)) {
            return $this->success(); //有下级的分类下方没数据，直接返回
        }
        $data = $this->photoArchivesService->getList($partCompanyId, $photoClassifyId, $perPage, $keyword, $type, $searchType);

        return $this->success($data);
    }

    /**
     * 添加照片档案
     *
     * @param Request $request
     * @return JsonResponse
     * @throws \App\Exceptions\ApiException
     * @author: lxk
     * @date: 2024/3/15 13:06
     */
    public function store(Request $request) : JsonResponse
    {
        $params = $request->all();
        if ($params['id'] && !isset($params['count'])) {
            if (!$this->photoArchivesService->updateData($params['id'], $params)) return $this->error('修改失败~');
            $event = "照片档案修改成功";
        } else {
            if (!$this->photoArchivesService->addNewData($params))  return $this->error('新增失败~');
            $event = request()->filled('id') ? "成功插入【{$params['count']}】条照片案卷" : "成功追加【{$params['count']}】条照片案卷";
        }
        $objectId = $params['id'] ?: 0;
        CommonService::addPhotoArchivesLog($event, $objectId, $params['part_company_id'], $params['photo_classify_id']);
        CommonService::isNeedUpdatePaperCount($params['part_company_id'], 1);

        return $this->success('', $event);
    }

    /**
     * 获取一条信息 $type 点击的类型：1第一卷, 2上一卷, 3下一卷, 4最后卷
     * $currentId 当前案卷目录id
     *
     * @param Request $request
     * @return JsonResponse
     * @author: lxk
     * @date: 2024/3/18 13:22
     */
    public function show(Request $request) : JsonResponse
    {
        $partCompanyId   = $request->input('part_company_id');
        $photoClassifyId = $request->input('photo_classify_id');
        $currentId       = $request->input('id');
        $type            = $request->input('type', 0);

        $data = $this->photoArchivesService->detail($partCompanyId, $photoClassifyId, $currentId, $type);

        return $this->success($data);
    }

    /**
     * 文字替换
     *
     * @param Request $request
     * @return JsonResponse
     * @author: lxk
     * @date: 2024/3/19 8:57
     */
    public function batchReplace(Request $request) : JsonResponse
    {
        $params = $request->all();

        $this->photoArchivesService->batchReplace($params);

        return $this->success('', '替换成功！');
    }

    /**
     * 检查案卷
     *
     * @param Request $request
     * @return JsonResponse
     * @throws ApiException
     * @author: lxk
     * @date: 2024/3/19 8:58
     */
    public function check(Request $request) : JsonResponse
    {
        $partCompanyId   = $request->input('part_company_id');
        $photoClassifyId = $request->input('photo_classify_id');

        $selectIds = $request->input('ids', '');
        $idStr     = implode(',', to_array($selectIds));
        $msg       = $this->photoArchivesService->checkData($partCompanyId, $photoClassifyId, $selectIds);

        CommonService::addProjectActionLog('检查案卷', $idStr, $partCompanyId, $photoClassifyId);

        return $this->success('', $msg); //检查完毕！异常数据已被标
    }

    /**
     * 批量导入照片 照片名称格式 档案号（J•JL2•5ZK123/169-1）和照片（0001）号组合， 如: J•JL2•5ZK123/169-1-0001
     *
     * @param Request $request
     * @return JsonResponse
     * @throws \App\Exceptions\ApiException
     * @author: lxk
     * @date: 2024/3/19 8:56
     */
    public function batchImportPhoto(Request $request) : JsonResponse
    {
        $partCompanyId   = $request->input('part_company_id');
        $photoClassifyId = $request->input('photo_classify_id');
        $file            = $request->file('file');
        $uploadResult    = (new AttachmentService())->upload($file, 'oss', $partCompanyId, $photoClassifyId, 'photo');
        $this->photoArchivesService->addNewPhoto($partCompanyId, $photoClassifyId, $uploadResult);

        return $this->success('', '上传照片成功！');
    }

    /**
     * 【照片档案】 问题标记
     *
     * @param Request $request
     * @return JsonResponse
     * @throws ApiException
     * @author: lxk
     * @date: 2024-09-12 17:15
     */
    public function problemMark(Request $request) : JsonResponse
    {
        $partCompanyId   = $request->input('part_company_id');
        $photoClassifyId = $request->input('photo_classify_id');
        $problem         = $request->input('problem');
        $ids             = to_array($request->input('ids'));

        $photoArchivesInstance = (new BaseService())->getPhotoArchiveInstance($partCompanyId, $photoClassifyId);
        if (!$photoArchivesInstance->whereIn('id', $ids)->update(['problem' => $problem])) {
            return $this->error('标记失败！');
        }
        $ids = implode(',', $ids);
        CommonService::addPhotoArchivesLog("照片档案问题标记:$problem", $ids, $partCompanyId, $photoClassifyId);

        return $this->success('', '标记成功！');
    }

    /**
     * 【照片档案】 问题已解决
     *
     * @param Request $request
     * @return JsonResponse
     * @throws ApiException
     * @author: lxk
     * @date: 2024-09-12 17:16
     */
    public function problemResolved(Request $request) : JsonResponse
    {
        $partCompanyId   = $request->input('part_company_id');
        $photoClassifyId = $request->input('photo_classify_id');
        $id              = $request->input('id');
        $problem         = $request->input('problem');

        $photoArchivesInstance = (new BaseService())->getPhotoArchiveInstance($partCompanyId, $photoClassifyId);
        if (!$photoArchivesInstance->where('id', $id)->update(['problem' => '', 'is_need_check'=>1])) {
            return $this->error('操作失败！');
        }
        CommonService::addPhotoArchivesLog("照片档案问题已解决:$problem", $id, $partCompanyId, $photoClassifyId);

        return $this->success('', '操作成功！');
    }

    /**
     * 【照片档案】 导入数据 注意！！！文件后缀名 xls 或者 xlsx 应该创建文件的时候指定，通过重命名修改文件后缀的的会导入失败
     *
     * @param Request $request
     * @return JsonResponse
     * @author: lxk
     * @date: 2024/3/19 8:55
     */
    public function import(Request $request) : JsonResponse
    {
        $projectId       = $request->input('project_id');
        $partCompanyId   = $request->input('part_company_id');
        $photoClassifyId = $request->input('photo_classify_id'); //照片分类
        try {
            if (PhotoClassifyService::isHaveChild($photoClassifyId)) {
                return $this->error('该分类有下级，禁止添加数据~');
            }
            $importCountKey = get_rand_str('import_photo_archives');
            $this->photoArchivesService->saveArchievesNoToRedis($partCompanyId, $photoClassifyId, $importCountKey); //获取全部照片档案号，放到redis，导入档案时进行比对，是否已存在

            Excel::import(new PhotoArchivesImport($projectId, $partCompanyId, $photoClassifyId, $importCountKey), $request->file('file'));
            $count = redis()->get($importCountKey);

            redis()->del($importCountKey);
            redis()->del('photo_archives_no' . $importCountKey);

            CommonService::addPhotoArchivesLog("导入照片案卷【{$count}】", 0, $partCompanyId, $photoClassifyId);
            return $this->success('', '成功导入【'.$count.'】条数据');
        }
        catch (Exception $exception) {
            ErrorMsgService::write($request, $request->url());
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 【照片档案 案卷】单个或批量都行 软删除，ids可以是以","逗号分割的字符串，也可以是数组形式
     * 删除若干数据后，剩余的数据序号和档案号重新排列，第一个序号为1 从小到大递增
     * @param Request $request
     * @return JsonResponse
     * @throws ApiException
     * @author: lxk
     * @date: 2024/3/19 9:02
     */
    public function destroyMore(Request $request) : JsonResponse
    {
        $partCompanyId   = $request->input('part_company_id');
        $photoClassifyId = $request->input('photo_classify_id');
        $bookArchiveIds  = to_array($request->input('ids'));

        if (!$this->photoArchivesService->delData($partCompanyId, $photoClassifyId, $bookArchiveIds)) {
            return $this->error('', '删除失败');
        }

        return $this->success('', '删除成功');
    }

}
